/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.freeter.common.util;

import com.alibaba.fastjson.JSON;
import com.freeter.modules.wiztalk.entity.InfEventEntity;
import com.freeter.modules.wiztalk.entity.InfModuleEntity;
import com.freeter.modules.wiztalk.service.InfEventService;
import com.freeter.modules.wiztalk.service.InfModuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-07-17 21:12
 */
@Component
public class RedisTool {
    @Autowired
    private InfModuleService infModuleService;
    @Autowired
    private InfEventService infEventService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> valueOperations;
    @Resource(name = "redisTemplate")
    private HashOperations<String, String, Object> hashOperations;
    @Resource(name = "redisTemplate")
    private ListOperations<String, Object> listOperations;
    @Resource(name = "redisTemplate")
    private SetOperations<String, Object> setOperations;
    @Resource(name = "redisTemplate")
    private ZSetOperations<String, Object> zSetOperations;


    /**
     * 页面map集合在缓存中的key值
     */
    private static final String MODULEMAP_KEY= "moduleMap";
    /**
     * 自定义事件map集合在缓存中的key值
     */
    private static final String EVENTMAP_KEY= "eventMap";
    /**
     * 机型map集合在缓存中的key值
     */
    private static final String MODELMAP_KEY= "modelMap";

    /**
     * 机型map集合在缓存中的key值
     */
    private static final String RUSERMODELMAP_KEY= "rUserModelMap";


    /**
     * 默认过期时长，单位：秒
     */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**
     * 不设置过期时长
     */
    public final static long NOT_EXPIRE = -1;

    public void set(String key, Object value, long expire) {
        valueOperations.set(key, toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value) {
        set(key, value, DEFAULT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = valueOperations.get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        return JSON.toJSONString(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }


    /**
     * 初始化缓存中的页面信息
     */
    public void initModuleMap() {
        List<InfModuleEntity> moduleList = infModuleService.selectListEntity();
        Map<String, String> moduleMap = new HashMap<String, String>();
        for (InfModuleEntity module : moduleList) {
            moduleMap.put(module.getAppId()+Constant.RUNG+module.getModuleName(), module.getId());
        }
        redisTemplate.opsForHash().putAll(MODULEMAP_KEY, moduleMap);
    }



    /**
     * 初始化缓存中的自定义事件信息
     */
    public void initEventMap() {
        List<InfEventEntity> eventList = infEventService.selectListEntity();
        Map<String, String> eventMap = new HashMap<String, String>();
        for (InfEventEntity event: eventList) {
            eventMap.put(event.getAppId()+Constant.RUNG+event.getEventName(), event.getId());
        }
        redisTemplate.opsForHash().putAll(EVENTMAP_KEY, eventMap);
    }







    /**
     * 根据产品与页面英文名称获取页面Id
     * @param appId   产品id
     * @param moduleName   页面英文名
     * @return
     */
    public String getModuleId(String appId,String moduleName) {
        Object moduleId = redisTemplate.opsForHash().get(MODULEMAP_KEY,appId+Constant.RUNG+ moduleName);
        return moduleId == null ? "" : moduleId.toString();
    }


    /**
     * 根据产品id与自定义事件英文名获取自定义事件id
     * @param appId  产品id
     * @param modelName   自定义事件英文名
     * @return
     */
    public String getEventId(String appId,String eventName) {
        Object eventId = redisTemplate.opsForHash().get(EVENTMAP_KEY,appId+Constant.RUNG+ eventName);
        return eventId == null ? "" : eventId.toString();
    }








}
